<template>
  <a-modal
    :title="modelTitle"
    :width="640"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          label="分组键名"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['group_key', {rules: [{required: true, min: 1, message: '分组键名不能为空'}]}]"
            placeholder="请输入分组键名" />
        </a-form-item>
        <a-form-item
          label="分组名"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['group_name', {rules: [{required: true, min: 1, message: '分组名称不能为空'}]}]"
            placeholder="请输入分组名" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { saveData } from '@/api/system/sysmenugroup'
import { pick } from 'lodash'
export default {
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      },
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      id: 0
    }
  },
  computed: {
    modelTitle: function () {
      if (this.id === 0) {
        return '新建分组'
      } else {
        return '编辑分组'
      }
    }
  },
  methods: {
    add () {
      this.visible = true
      this.id = 0
      const { form: { resetFields } } = this
      this.$nextTick(() => {
        resetFields()
      })
    },
    edit (record) {
      this.visible = true
      this.id = record.group_id
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue(pick(record, ['group_key', 'group_name']))
      })
    },
    handleSubmit () {
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          saveData(Object.assign(values, { group_id: this.id })).then(res => {
            this.confirmLoading = false
            if (res.code === 0) {
              this.visible = false
              this.$message.success(res.message)
              this.$emit('ok', values)
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
    }
  }
}
</script>
